package com.grayscale.core.rule;

import com.grayscale.core.adapt.GrayScaleRuleAdapt;
import com.grayscale.core.enums.GrayScaleTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 是否 包含、不包含 某个值
 * @author liuli
 * @date 2022/2/23
 */
public class GrayScaleServerNodeRule implements GrayScaleRuleAdapt {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Override
    public boolean process(String... parameter) {
        if (!check(parameter[0])){
            return false;
        }
        if (StringUtils.isBlank(parameter[3])){
            log.error("配置的KEY的值为空");
            return false;
        }
        String str[] = parameter[0].split(",");
        GrayScaleTypeEnum grayScaleTypeEnum = GrayScaleTypeEnum.getByType(parameter[1]);
        switch (grayScaleTypeEnum) {
            case SERVER_IN:
                for (int i = 0; i < str.length; i++) {
                    if (str[i].equals(parameter[3])){
                        return true;
                    }
                }
                return false;
            case SERVER_NOT_IN:
                for (int i = 0; i < str.length; i++) {
                    if (str[i].equals(parameter[3])){
                        return false;
                    }
                }
                return true;
        }
        return false;
    }

    @Override
    public boolean check(String parameter) {
        try {
            String str[] = parameter.split(",");
            if (str.length <=0){
                return false;
            }
            return  true;
        } catch (Exception e) {
            log.error("parameter format error:{} {}",parameter,e);
            return false;
        }
    }
}
